package com.flong.lambda;

import com.alibaba.fastjson.JSON;
import com.flong.DataUtils;
import com.flong.vo.Person;
import org.junit.Test;

import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @Author:liangjl
 * @Date: 2020/6/21-16:42
 * @Eamil:jilongliang@sina.com
 * @Description: stream has already been operated upon or closed
 * max、min、count是一个终极操作方法，所以使用了之后再进行使用的话，它的流以及进行关闭，使用不能进行同时进行使用.
 */
public class Test8 {

    @Test
    public void test1() {

        Stream<Integer> intStream = Stream.of(10, 110, 101, 121);
        //1、统计有多条数据
        //long count = intStream.count();
        Integer max = intStream.max(Comparator.comparing(Integer::intValue)).get();
        //Integer min = intStream.min(Comparator.comparing(Integer::intValue)).get();

        //System.out.println("count=" + count);
        System.out.println("max=" + max);
        // System.out.println("min=" + min);
    }


    @Test
    public void mapToInt1() {
        //Integer占用的内存比int多，在Stream流操作中会自动装箱和拆箱
        Stream<Integer> intStream = Stream.of(10, 110, 101, 121);
        //IntStream：内部操作的是int类型的数据，就可以节省内存，减少自动装箱和拆箱
        IntStream intStream1 = intStream.mapToInt(Integer::intValue);
    }

    @Test
    public void mapToInt2() {

        int asInt = DataUtils.personList().stream().mapToInt(Person::getAge).max().getAsInt();
        System.out.println(asInt);

    }


    @Test
    public void minBy() {
        Stream<Person> personStream = DataUtils.personStream();
        Optional<Person> personOptional = personStream.collect(Collectors.minBy((s1, s2) -> s1.getAge() - s2.getAge()));
        Person person = personOptional.get();
        System.out.println("最小值:" + JSON.toJSON(person));
    }

    @Test
    public void maxBy() {
        Stream<Person> personStream = DataUtils.personStream();
        Optional<Person> personOptional1 = personStream.collect(Collectors.maxBy((s1, s2) -> s1.getAge() - s2.getAge()));
        Person person1 = personOptional1.get();
        System.out.println("最大值：" + JSON.toJSON(person1));

    }
    @Test
    public void suming() {
        Stream<Person> personStream = DataUtils.personStream();
        //计算所有人的总年龄
        Integer totalAge = personStream.collect(Collectors.summingInt(s -> s.getAge()));
        System.out.println("所有人的总年龄：" + totalAge);

    }
    @Test
    public void averaging() {
        Stream<Person> personStream = DataUtils.personStream();
        //计算所有人的平均年龄
        Double averaginAge = personStream.collect(Collectors.averagingDouble(s -> s.getAge()));
        System.out.println("所有人的平均年龄：" + averaginAge);

    }

    @Test
    public void counting() {
        Stream<Person> personStream = DataUtils.personStream();
        //统计所有人的数量
        Long count = personStream.collect(Collectors.counting());
        System.out.println("统计所有人的数量：" + count);
    }

}